package com.example.springbootshiro.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springbootshiro.dao.UserMapper;
import com.example.springbootshiro.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


public class ShiroRealm extends AuthorizingRealm {
    private static final Logger logger = LoggerFactory.getLogger(ShiroRealm.class);

    @Autowired
    private UserMapper userMapper;


    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权");
        logger.info("========执行授权=============");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser =(User) subject.getPrincipal(); //拿到User对象
        //设置当前用户的权限
        if (currentUser.getPerms()!=null) {
            info.addStringPermission(currentUser.getPerms());//如果当前用户有权限，就添加授权
            return info;
        }
        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //System.out.println("执行认证");
        logger.info("========执行认证=============");
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("name", token.getUsername());
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
            return null;
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        ByteSource salt = ByteSource.Util.bytes(user.getSalt());
        simpleAuthenticationInfo.setCredentialsSalt(salt);
        SecurityUtils.getSubject().getSession(true).setAttribute("uid", user.getId());
        SecurityUtils.getSubject().getSession(true).setAttribute("loginUser", user.getName());
        return simpleAuthenticationInfo;
    }
}
